#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

void SeqListInit(SL* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->capacity = 0;
	ps->size = 0;
}
void SeqLisstDestory(SL* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->capacity = ps->size = 0;
}

void SeqListPrint(SL* ps)
{
	assert(ps);

	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->arr[i]);
	}

	printf("\n");
}

void SLCheckCapacity(SL* ps)
{
	assert(ps);

	if (ps->capacity == ps->size)
	{
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SLDataType* tmp = (SLDataType*)realloc(ps->arr, sizeof(SLDataType) * newCapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->arr = tmp;
		ps->capacity = newCapacity;
	}
}
void SeqListPushBack(SL* ps, SLDataType val)
{
	SLCheckCapacity(ps);

	ps->arr[ps->size] = val;
	ps->size++;
}
void SeqListPushFront(SL* ps, SLDataType val)
{
	SLCheckCapacity(ps);

	int end = ps->size;

	while (end > 0)
	{
		ps->arr[end] = ps->arr[end - 1];
		end--;
	}

	ps->arr[0] = val;
	ps->size++;
}

void SeqListPopBack(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);

	ps->size--;
}
void SeqListPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);

	int start = 0;

	while (start < ps->size -1)
	{
		ps->arr[start] = ps->arr[start + 1];
		start++;
	}

	ps->size--;
}

int SeqListFind(SL* ps, SLDataType val)
{
	assert(ps && ps->size > 0);

	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == val)
		{
			return i;
		}
	}

	return -1;
}
void SeqListInsert(SL* ps, int pos, SLDataType val)
{
	assert(ps);

	int end = ps->size;
	while (end >= pos)
	{
		ps->arr[end] = ps->arr[end - 1];
		end--;
	}

	ps->arr[pos] = val;
	ps->size++;
}
void SeqListErase(SL* ps, int pos)
{
	assert(ps);
	assert(ps->size > 0);

	int start = pos-1;

	while (start < ps->size-1)
	{
		ps->arr[start] = ps->arr[start + 1];
		start++;
	}

	ps->size--;
}